﻿#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
#include <iostream>
#include <future>
#include <map>
#include "windows_helper.h"

HHOOK keyboardHook = NULL;

void openWt();
void backKeyEvent();

void openWt() {
    TCHAR	pathString[MAX_PATH] = { 0 };
    getCurrentDir(pathString);

    constexpr TCHAR processName[] = { L"WindowsTerminal.exe" };
    DWORD pid = getProcessId(processName);
    if (ULONG_MAX == pid) {
        TCHAR	workPath[MAX_PATH] = { 0 };
        lstrcat(workPath, L"-d \"");
        lstrcat(workPath, pathString);
		lstrcat(workPath, L"\"");
        ShellExecute(NULL, NULL, TEXT("wt"), workPath, NULL, SW_SHOW);
        return;
    }
    HWND hwnd = setForegroundWindow(pid);

    TCHAR	cmdString[MAX_PATH] = { 0 };
    lstrcat(cmdString, L"cd \"");
    lstrcat(cmdString, pathString);
    lstrcat(cmdString, L"\"\r\n");

    setClipData(cmdString);
    constexpr int v = 0x41 + ('v' - 'a');

	keybd_event(VK_LMENU, 0, KEYEVENTF_KEYUP, 0);
	backKeyEvent();

    keybd_event(VK_LCONTROL, 0, 0, 0);
    keybd_event(v, 0, 0, 0);
    keybd_event(v, 0, KEYEVENTF_KEYUP, 0);
    keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);

	backKeyEvent();
};

void backKeyEvent() {

	constexpr int a = 0x41;

	for (size_t i = 0; i < 2; i++)
	{
		//ctrl + a
		keybd_event(VK_LCONTROL, 0, 0, 0);
		keybd_event(a, 0, 0, 0);
		keybd_event(a, 0, KEYEVENTF_KEYUP, 0);
		keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);
		//back
		keybd_event(VK_BACK, 0, 0, 0);
		keybd_event(VK_BACK, 0, KEYEVENTF_KEYUP, 0);
	}
};

int main()
{
	WPARAM hotId = 888000;	
	std::map<WPARAM, char> hotKeyMap{
			{hotId++,'t'},
			{hotId++,'x'},
	};
	for (auto iter = hotKeyMap.begin(); iter!= hotKeyMap.end(); iter++)
	{
		int key = 0x41 + (iter->second - 'a');
		//MOD_ALT | MOD_CONTROL
		if (!RegisterHotKey(NULL, iter->first, MOD_ALT, key)) {
			MessageBox(NULL, L"RegisterHotKey error.", TEXT("wt_quick"), 0);
			return 0;
		}
	}
	
	MSG msg = { 0 };
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (msg.message == WM_HOTKEY && hotKeyMap.count(msg.wParam))
		{
			switch (hotKeyMap[msg.wParam])
			{
			case 'x':
				MessageBox(NULL, L"wt_quick exit.", TEXT("wt_quick"), 0);
				exit(0);
			case 't':
                openWt();
			default:
				break;
			}
			
		}
	}
	
	return 0;
}